import {createSlice, createAsyncThunk} from "@reduxjs/toolkit";
import {RootState} from "@/app/store";
import {userLoginAPI, userLogoutAPI} from "@api/User";

export interface LoginParams {
    account: string;
    password: string;
}

// 1. 定义初始化状态
const initialState = {
    // 应该从localStorage中读取token数据，有就用，没有空串
    token: localStorage.getItem("token") || "", // 用户唯一标识
    name: "mkbk", // 用户名
    avatar: "https://raw.githubusercontent.com/tmkbk/images/main/202411111914582.png" // 用户头像
};

// 异步action
// 登录
export const loginAsync = createAsyncThunk("user/loginAsync", ({account, password}: LoginParams) => {
    const res = userLoginAPI({
        account,
        password
    });
    return res
});
// 登出
export const logoutAsync = createAsyncThunk("user/logoutAsync", () => {
    return userLogoutAPI();
})
// 2. 创建redux模块
const userSlice = createSlice({
    name: "user",
    initialState,
    reducers: {},
    extraReducers: (builder) =>
        builder.addCase(loginAsync.fulfilled, (state, action) => {
                const token = action.payload.data.data.token;
                // 将token存储在redux中
                state.token = token;
                // 将token存储在localStorage中
                localStorage.setItem("token", token);
            })
            .addCase(logoutAsync.fulfilled, (state, action) => {
                    state.token = "";
                    state.name = "";
                    state.avatar = "";
                    localStorage.removeItem("token");
                }
            )
});

export const selectUser = (state: RootState) => state.user;

// 3. 将redux模块的reducer函数暴露出去，汇总
export default userSlice.reducer;
